#include "tcpsrv.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>

extern char *squidhome;
extern char *squidpid;
extern char *squidswapfile;
extern char *squidversion;
extern char *squidgroup[MAX_GROUP];

int process_cmd(struct conn_client *client, unsigned char *cmd)
{
	int i;
	char act[4]={};
	char key[8]={};
	int cstrlen = 0;
	int loop = 1;
	int interval = 1;
	char ccmd[255]={};
	char url[255]={};
	char version[100]={};
	char squidbin[200]={};
	char squidstart[250]={};
	char squidstop[250]={};
	char value[255]={};

	//printf("cmd:%s\n",cmd);

	if (ccmd){sscanf(cmd,"%s",ccmd);}

	//printf("chk_cmd_len:%s,%d\n",ccmd,strlen(ccmd));

	sprintf(squidbin,"%ssbin/squid",squidhome);
	sprintf(squidstart,"%s -CDNd1&",squidbin);
	sprintf(squidstop,"%s -k shutdown",squidbin);

	if (strcmp(ccmd,"quit")==0){
		conn_free(client);
	}
	else if (strcmp(ccmd,"version")==0){
		sprintf(version,"VERSION %s",squidversion);
		i = conn_send(client,version);
	}
	else if (strcmp(ccmd,"flush_all")==0){
		system(squidstop);
		system(squidstop);
		touchcache(squidswapfile);
		system(squidstart);
		i = conn_send(client,"OK");
	}
	else if (strcmp(ccmd,"set")==0){
		sscanf(cmd,"%3s %[A-Z] %d %d %d\r\n%s",act,key,&loop,&interval,&cstrlen,value);
		//printf("act:%s,key:%s,loop:%d,interval:%d,cstrlen:%d,value:%s\n",act,key,loop,interval,cstrlen,value);
		if (loop == 0){
			loop = 1;
		}
		else{
			loop = 0;
			if (interval<MIN_EVENT_TIME){
				interval=MIN_EVENT_TIME;
			}
		}
		if (strcmp(key,"PURGE") == 0){
			sprintf(url,"PURGE://%s",value);
			int id = event_item_add(loop,interval,url);
			//struct event_item * item = event_item_find(id);
			//printf("%d %d %d %d %s\n",id ,item -> start_time, item -> loop, item -> interval, item -> cmd);
			i = conn_send(client, "STORED");
		}
		else if (strcmp(key,"PURGEDIR") == 0){
			sprintf(url,"PURGEDIR://%s",value);
			int id = event_item_add(loop,interval,url);
			i = conn_send(client, "STORED");
		}
		else{
			i = conn_send(client,"ERROR");
		}
	}
	else if(strcmp(ccmd,"get")==0){
		sscanf(cmd,"%3s %[A-Z] %d %d %d\r\n%s",act,key,&loop,&interval,&cstrlen,value);
		if (strcmp(key,"START")==0){
			system(squidstart);
			i = conn_send(client,"VALUE START 0 2\r\nOK\r\nEND");
		}
		else if (strcmp(key,"STOP")==0){
			system(squidstop);
			system(squidstop);
			i = conn_send(client,"VALUE STOP 0 2\r\nOK\r\nEND");
		}
		else {
			i = conn_send(client,"ERROR");
		}
	}
	else{
		i = conn_send(client, "ERROR");
	}

	return 0;
}
int main(int argc, char **argv)
{
	parsexml();
//	printf("%s\n",squidhome);
//	sleep(5);
	conn_init(1);
}
